package com.rocksdata.mc.business;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.database.PayrollDBManager;
import com.rocksdata.mc.http.HttpClient;
import com.rocksdata.mc.database.DatabaseManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 陈堂正 on 2017/8/15.
 */

public class PayrollManager implements BusinessInterface.IPayrollManager {
    private static final String URL_GET_PAYROLL_INFO = BuildConfig.HOST + "/payroll";

    private static BusinessInterface.IPayrollManager instance;

    private PayrollDBManager dbManager;

    public synchronized static BusinessInterface.IPayrollManager getInstance(){
        if(instance == null){
            instance = new PayrollManager();
        }
        return instance;
    }

    private PayrollManager(){
        dbManager = DatabaseManager.getPayrollDBManager();
    }

    @Override
    public void getPayrollInfo(String yearMonth, Class payrollClass, BusinessInterface.OnBusinessResultListener listener){
        String jsonData = dbManager.getPayrollInfo(yearMonth);
        if(TextUtils.isEmpty(jsonData)){
            getPayrollInfoRemote(yearMonth, payrollClass, listener);
        }else{
            Object obj = JSON.parseObject(jsonData, payrollClass);
            listener.onBusinessResult(true, obj, null);
        }
    }

    private void getPayrollInfoRemote(final String yearMonth, Class payrollClass, final BusinessInterface.OnBusinessResultListener listener){
        Map<String, Object> map = new HashMap<>();
        map.put("userID", UserInfoManager.getCurrentUserId());
        map.put("yearMonth", yearMonth);
        HttpClient.get(URL_GET_PAYROLL_INFO, map, payrollClass, new HttpClient.OnHttpResultListener(){

            @Override
            public void onResult(boolean isSuccess, List data, String msg) {
                if(isSuccess){
                    if(data != null && data.size() > 0) {
                        dbManager.savePayrollInfo(yearMonth, JSON.toJSONString(data.get(0)));
                        listener.onBusinessResult(true, data.get(0), msg);
                        return;
                    }
                }
                listener.onBusinessResult(false, null, msg);
            }
        });
    }


}
